package com.ruoyi.common.utils.mobile.weixin.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.common.utils.FBSStringUtil;
import com.ruoyi.common.utils.WeixinUtils;
import com.ruoyi.common.utils.mobile.IMobileMsg;

/**
 * 功能：
 *
 * @author：Administrator
 * @create：2019/6/26/026 15:19
 * @version：2019 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
public abstract class BaseMsgService implements IMsgService{
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	protected abstract String getUrl();

	@Override
	public void pushMsg(IMobileMsg msgTemplate) {
		final String msgContent = msgTemplate.serialized();
		new Thread(){
			@Override
			public void run() {
				try {
					HttpURLConnection connection = WeixinUtils.createConnection(FBSStringUtil.format(getUrl(),AppBeanInjector.wxMpService.getAccessToken()), "POST");
					//发送链接
					connection.connect();
					OutputStream outputStream = connection.getOutputStream();
					outputStream.write(msgContent.getBytes("UTF-8"));//传入参数
					InputStream inputStream = connection.getInputStream();
					int size = inputStream.available();
					byte[] bytes = new byte[size];
					inputStream.read(bytes);
					String result = new String(bytes, "UTF-8");
					logger.debug("发送的微信消息:{}",msgContent);
					logger.debug("发送微信消息的结果:{}",result);
					//刷新流
					outputStream.flush();
					//关闭输入流
					inputStream.close();
					//关闭输出流
					outputStream.close();
					//断开连接
					connection.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}
